const express = require('express')
const moment = require('moment-timezone')
const models = require('../models')

moment.tz.setDefault("Asia/Shanghai")

const router = express.Router()

function utcNow() {
    return new Date((moment().format("yyyy-MM-DDTHH:mm:00") + 'Z'))
}

function utc2locale(utcDate) {
    return moment(utcDate).subtract(8, 'hours')
}

function utc2Date(utcDate) {
    return new Date((moment(utcDate).format("yyyy-MM-DDTHH:mm:00") + 'Z'))
}

function timeStamp(utcDate) {
    return Math.round(utcDate.getTime() / 1000) - 8 * 60 * 60
}

function addUsageDays(dev, qrCode) {
    if (dev.expireDate && utc2locale(utcNow()).isBefore(utc2locale(dev.expireDate))) {
        dev.expireDate = utc2Date(utc2locale(dev.expireDate).add(dev.consumptionSpeed, 'hours'))
    } else {
        dev.expireDate = utc2Date(utc2locale(utcNow()).add(dev.consumptionSpeed, 'hours'))
    }
    qrCode.status = 20
    qrCode.updatedAt = utcNow()
    qrCode.save()
    dev.save()
    models.ScanLog.create({ codeId: qrCode.id, deviceId: dev.id, createdAt: utcNow(), status:0 })
    return timeStamp(dev.expireDate)
}

router.post('/update', async (req, res) => {
    if (req.body.imei) {
        let dev = await models.Device.findOne({ where: { imei: req.body.imei } })
        if (!dev) {
            let createdAt = utcNow()
            dev = await models.Device.create({ imei: req.body.imei, createdAt: createdAt, updatedAt: createdAt })
        }
        dev.iccid = req.body.iccid
        dev.ab = req.body.ab
        dev.updatedAt = utcNow()
        dev.save()
        console.log(dev.toJSON())
        let term = 0
        if (dev.expireDate) {
            term = timeStamp(dev.expireDate)
        }
        res.json({ status: dev.status, term: term })
    } else {
        res.json({ status: 4, msg: '请求参数不完整' })
    }
})

router.post('/scan', async (req, res) => {
    if (req.body.imei && req.body.code) {
        let qrCode = await models.QRCode.findOne({ where: { code: req.body.code } })
        let dev = await models.Device.findOne({ where: { imei: req.body.imei } })
        if (!dev) {
            res.json({ status: 3, msg: "设备未注册" })
            return
        }
        if (!qrCode) {
            res.json({ status: 5, msg: "非法二维码" })
            return
        }
        if (qrCode.status == 10) {
            if (qrCode.expireDate) {
                if (utc2locale(utcNow()).isAfter(utc2locale(qrCode.expireDate))) {
                    // models.ScanLog.create({ codeId: qrCode.id, deviceId: dev.id, status: 55, createdAt: utcNow() })
                    res.json({ status: 5, msg: "二维码已过期" })
                } else {
                    let term = addUsageDays(dev, qrCode)
                    res.json({ status: 0, term: term })
                }
            } else {
                let term = addUsageDays(dev, qrCode)
                res.json({ status: 0, term: term })
            }
        } else if (qrCode.status == 20) {
            // models.ScanLog.create({ codeId: qrCode.id, deviceId: dev.id, status: 4, createdAt: utcNow() })
            res.json({ status: 4, msg: "二维码已被使用" })
        }

    } else {
        res.json({ status: -1, msg: "请求参数不符" })
    }
})

router.post('/open', async (req, res) => {
    if (req.body.imei) {
        let dev = await models.Device.findOne({ where: { imei: req.body.imei } })
        if (!dev) {
            res.json({ status: 3, msg: "设备不存在" })
        } else {
            let operations = await models.OperationLog.findAll({ where: { deviceId: dev.id } })
            let count = 0
            for (let i = 0; i < operations.length; i++) {
                const ele = operations[i];
                if (ele.status == 0 && utc2locale(ele.createdAt).add(90, 'days').isAfter(utc2locale(utcNow()))) {
                    count++
                }
            }
            if (count >= 3) {
                models.OperationLog.create({ deviceId: dev.id, status: 7, createdAt: utcNow() })
                res.json({ status: 7, count: count })
            } else {
                models.OperationLog.create({ deviceId: dev.id, status: 0, createdAt: utcNow() })
                count++
                res.json({ status: 0, count: count })
            }
        }
    } else {
        res.json({ status: -1, msg: "请求参数不符" })
    }
})

module.exports = router
